package com.roger.uia.helper;

import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.support.test.uiautomator.UiWatcher;
import android.util.Log;
import com.roger.uia.helper.util.FileUtils;
import org.junit.Assert;
import static com.roger.uia.helper.UiBase.mDevice;

public class UiWatch {
    private static final String TAG = "Test" + UiWatch.class.getSimpleName();

    public static UiWatch getWatcher() {
        return new UiWatch();
    }

    /**
     * register UiWatch
     * @param name     UiWatch name
     * @param obj1     exist obj
     * @param obj2     click obj
     * @param isBug    if it is a bug
     */
    private void runUiWatcher(final String name, final UiObject obj1, final UiObject obj2, final boolean isBug){
        mDevice.registerWatcher(name, new UiWatcher() {
            @Override
            public boolean checkForCondition() {
                if(obj1.exists()){
                    try {
                        Log.d(TAG,"exist: " + name);
                        FileUtils.takeScreenPicTo(UiBase.filePath + "UiTest/pic/", name);
                        obj2.clickAndWaitForNewWindow();
                    } catch (UiObjectNotFoundException e) {
                        e.printStackTrace();
                    }
                    if (isBug)  Assert.fail("this is a bug!");
                    return true;
                }
                return false;
            }
        });
    }

    /**
     * remove UiWatch
     * @param name   UiWatch name
     */
    private void removeUiWatcher(String name) {
        if (mDevice.hasWatcherTriggered(name)) mDevice.removeWatcher(name);
    }

    public void runErrorWatcher(){
        String errorTip = "(?i).*isn't responding.*|.*没有响应.*|.*keeps stopping.*|.*has stopped|.*停止运行";
        String closeBtn = "(?i).*close.*|.*关闭.*";
        UiObject obj1 = mDevice.findObject(new UiSelector().textMatches(errorTip));
        UiObject obj2 = mDevice.findObject(new UiSelector().textMatches(closeBtn));
        runUiWatcher("Error",obj1,obj2,true);
    }

    public void removeErrorWatcher(){
        removeUiWatcher("Error");
    }

    public void runSpecialWatcher(){
        String specialTip = "(?i)Usage statistics|用户服务协议和隐私政策概要|No, thanks|不了，谢谢|我知道了|以后再说|暂不升级|Update later|Login Weibo|登录微博|.*这将会产生数据流量费用.*";
        String specialBtn = "(?i)NO THANKS|同意|No, thanks|不了，谢谢|我知道了|以后再说|暂不升级|Update later|Browsing|随便看看";
        UiObject obj1 = mDevice.findObject(new UiSelector().textMatches(specialTip));
        UiObject obj2 = mDevice.findObject(new UiSelector().textMatches(specialBtn));
        runUiWatcher("Special",obj1,obj2,false);
    }

    public void removeSpecialWatcher(){
        removeUiWatcher("Special");
    }

}
